from random import randint

from django.shortcuts import render
from django.views import View
from django import http
from django_redis import get_redis_connection

from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RETCODE, err_msg
from celery_tasks.sms.tasks import send_sms_code

# 创建日志
import logging

logger = logging.getLogger('django')


class ImageCodeView(View):
    def get(self, request, uuid):
        # UUID 用于区别redis中的图形验证码属于哪个手机
        # 1. 调用sdk 生成图形验证码
        # name: 唯一标识, text: 图形验证码字符串, image: 图形验证码图形bytes数据
        name, text, image = captcha.generate_captcha()
        # 2. 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 3. 将图形验证码 字符串存储到redis中
        redis_conn.setex(uuid, 300, text)
        # 4. 响应图片数据
        return http.HttpResponse(image, content_type='image/png')


class SMSCodeView(View):
    def get(self, request, mobile):

        # 尝试获取短信验证码标识, 判断是否60秒内已经发送过标识
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '频繁发送短信'})

        # 1. 接收
        query_dict = request.GET
        image_code_client = query_dict.get('image_code')
        uuid = query_dict.get('uuid')

        # 2. 校验
        if all([image_code_client, uuid]) is False:
            return http.HttpResponseForbidden('缺少必传参数')
        # 2.1 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        # 2.2 获取redis中图形验证码字符
        image_code_server_bytes = redis_conn.get(uuid)

        # 管道
        pl = redis_conn.pipeline()

        # 一次性图形验证码
        pl.delete(uuid)
        # 3.2 判断redis中的图形验证码是否已过期
        if image_code_server_bytes is None:
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码已过期'})
        # 3.3 将bytes类型转换成str (从redis中获取出来的数据都是bytes  str, dict, list, set)
        image_code_server = image_code_server_bytes.decode()
        # 判断用户填写验证码和redis取的是否一致
        if image_code_client.lower() != image_code_server.lower():
            return http.JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码填写错误'})

        # 随机验证码
        sms_code = '%06d' % randint(0, 999999)
        # 创建到日志里
        # CCP().send_template_sms("接收短信的手机号", ['验证码', '提示用户短信验证码的过期时间(分钟)'], '模板id')
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # send_sms_code(mobile, sms_code)
        logger.info(sms_code)

        # 触发异步任务
        send_sms_code.delay(mobile, sms_code)
        # 存储短信验证码到redis,供验证
        pl.setex('sms_%s' % mobile, 300, sms_code)

        # 存储短信验证码60秒的标识
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': "OK"})






